package utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JavaProcessor {
    private Process process;
    private BufferedReader reader;
    private BufferedWriter writer;
    private final String pipeName = "MyPipe";
    private final String scriptPath = "D:/yolov5/VOCData4/newAutomation1.py";

    public void initialize() throws IOException {
        // 创建命名管道
        File pipeFile = new File(pipeName);
        pipeFile.createNewFile();

        // 启动Python程序
        List<String> command = new ArrayList<>();
        command.add("cmd");
        command.add("/c");
        command.add("cd /d D:\\yolov5 && activate yolov5 && cd VOCData4 && python");
        command.add(scriptPath);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        process = processBuilder.start();
        InputStream inputStream = process.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        OutputStream outputStream = process.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    }

    public String processImage(String imagePath) throws IOException {
        // 向Python程序发送图片路径
        writer.write(imagePath);
        writer.newLine();
        writer.flush();

        // 等待Python程序处理完毕并返回结果
        StringBuilder resultBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            resultBuilder.append(line).append("\n");
            if (line.equals("Detection finished.")) {
                break;
            }
        }

        return resultBuilder.toString();
    }

    public void sleep() throws IOException {
        // 向Python程序发送休眠指令
        writer.write("sleep");
        writer.newLine();
        writer.flush();
    }

    public void close() throws IOException {
        // 关闭管道和子进程
        writer.close();
        reader.close();
        process.destroy();

        // 删除命名管道
        File pipeFile = new File(pipeName);
        pipeFile.delete();
    }
}
